#!/usr/bin/python
#- bcp2xmmsskin (060622a, Python version (Linux only (afaik)))
#- (converted from bcp2gnome060508g.wxb)

import os
import sys

#- Bug: i can't run it from /usr/bin/ just like a command (...?)

finp_st=sys.argv[1]
chbcp_st=finp_st
debug=0

#- i want to put a '--help' option as argv option, but i don't know about it
varghlp=0;basepal=1;txttmpl=1
if finp_st=="--help":
  varghlp=1

if varghlp==0:
  #- './' as opcional to '/usr/bin/' (last prioritary)
  flg=0;tm_st="./Base.BaseColorPalette"
  if os.path.isfile(tm_st):fbase_st=tm_st;flg=1
  if debug==1:print"base: ./"
  tm_st="/usr/bin/Base.BaseColorPalette"
  if os.path.isfile(tm_st):fbase_st=tm_st;flg=1
  if debug==1:print"base: /usr/bin/"
  if flg==0:
    basepal=0
  #- './' as opcional to '/usr/bin/' (last prioritary)
  flg=0;tm_st="./sqc_pekwm_template.txt"
  if os.path.isfile(tm_st):finp_st=tm_st;flg=1
  if debug==1:print"template: ./"
  tm_st="/usr/bin/sqc_pekwm_template.txt"
  if os.path.isfile(tm_st):finp_st=tm_st;flg=1
  if debug==1:print"template: /usr/bin/"
  if flg==0:
    txttmpl=0

#- this reader is assuming only one gamma value is set - only the last #define value will be considered
#- this reader reads 2 files, first the Base one, and later the Custom one 

#----------------------------------------------------------------------------------------
#- functions ----------------------------------------------------------------------------
def suffixreplacer(a_st,b_st):
  lct1=a_st.rfind(".");lct2=a_st.rfind("/")
  if lct1>-1 and lct1>lct2:a_st=a_st[:lct1]
  a_st=a_st+b_st
  return a_st
def locstrinfo(a_st,b_st,c_st):
  adra=0;adrb=0;d_st=""
  while adrb<=len(a_st) and adrb<len(b_st):
    if debug==1:print adra,adrb
    if a_st[adra]==b_st[adrb]:
      adrb=adrb+1
    adra=adra+1
  while a_st[adra]!=c_st[0]:
    d_st=d_st+a_st[adra]
    adra=adra+1
  return d_st
def hexvl(a_st):
  a_st=a_st.lower();tmpr=0;hx_st="0123456789abcdef";hx_st=hx_st.lower()
  for i in range(0,len(a_st),1):tmpr=(tmpr*16)+hx_st.find(a_st[i])
  return tmpr
def fixhxc(va):
  tm_st="000000"+hex(va).lstrip("0x");tm_st="#"+tm_st[len(tm_st)-6:]
  return tm_st.upper()
def fixhex(va,sz):
  tml_st=""
  for i in range (0,sz,1):tml_st=tml_st+"0"
  tml_st=tml_st+hex(va).lstrip("0x");tml_st=tml_st[len(tml_st)-sz:]
  return tml_st.upper()
def shade(a_st,kw_st,shd):
  a_st="000000"+a_st;a_st=a_st[len(a_st)-6:]
  a_st=a_st.lower();tmpr=0;hx_st="0123456789abcdef";hx_st=hx_st.lower()
  rv=(hx_st.find(a_st[0])*16)+hx_st.find(a_st[1])
  gv=(hx_st.find(a_st[2])*16)+hx_st.find(a_st[3])
  bv=(hx_st.find(a_st[4])*16)+hx_st.find(a_st[5])
  if kw_st.lower()=="k":
    rv=int(rv*shd);gv=int(gv*shd);bv=int(bv*shd)
  else:
    rv=int(255-((255-rv)*shd));gv=int(255-((255-gv)*shd));bv=int(255-((255-bv)*shd))
  hc_st="000000"+hex(rv*65536+gv*256+bv).lstrip("0x")
  return hc_st[len(hc_st)-6:]

#----------------------------------------------------------------------------------------
#- defining theme name ------------------------------------------------------------------
if varghlp==0:
  themename_st=suffixreplacer(chbcp_st,"")

#----------------------------------------------------------------------------------------
#- converter code start -----------------------------------------------------------------
if varghlp==0 and (txttmpl==1 and basepal==1):
  #----------------------------------------------------------------------------------------
  #- reads #define values from Base and Custom --------------------------------------------
  fovl_stl=[""]*2 #- dim fovl_stl(2)
  fovl_stl[0]=fbase_st;fovl_stl[1]=chbcp_st
  for foid in range(0,2,1):
    inpfile=open(fovl_stl[foid],"r")
    print "loading",str(fovl_stl[foid])
    lcntr=0
    while True:
      text_st=inpfile.readline();lcntr=lcntr+1
      #- print "readed line lenght:"+str(len(text_st)),str(lcntr)
      if len(text_st)==0:break
      text_st=" "+text_st.strip()+"      "
      cm01_st=locstrinfo(text_st," "," ")
      cm02_st=locstrinfo(text_st," # "," ")
      cm03_st=locstrinfo(text_st," #  #"," ")
      if cm02_st.lower()=="linkforegroundcolor"          :LinkForegroundColor          =hexvl(cm03_st)
      if cm02_st.lower()=="activelinkforegroundcolor"    :ActiveLinkForegroundColor    =hexvl(cm03_st)
      if cm02_st.lower()=="visitedlinkforegroundcolor"   :VisitedLinkForegroundColor   =hexvl(cm03_st)
      if cm02_st.lower()=="basicbackground"              :BasicBackground              =hexvl(cm03_st)
      if cm02_st.lower()=="referencetext"                :ReferenceText                =hexvl(cm03_st)
      if cm02_st.lower()=="textforeground"               :TextForeground               =hexvl(cm03_st)
      if cm02_st.lower()=="textfieldbackground"          :TextFieldBackground          =hexvl(cm03_st)
      if cm02_st.lower()=="readonlybackground"           :ReadOnlyBackground           =hexvl(cm03_st)
      if cm02_st.lower()=="buttonbackground"             :ButtonBackground             =hexvl(cm03_st)
      if cm02_st.lower()=="scrollbartroughcolor"         :ScrollBarTroughColor         =hexvl(cm03_st)
      if cm02_st.lower()=="scrollbarcontrolbackground"   :ScrollBarControlBackground   =hexvl(cm03_st)
      if cm02_st.lower()=="indicatorbackground"          :IndicatorBackground          =hexvl(cm03_st)
      if cm02_st.lower()=="radiocolor"                   :RadioColor                   =hexvl(cm03_st)
      if cm02_st.lower()=="checkcolor"                   :CheckColor                   =hexvl(cm03_st)
      if cm02_st.lower()=="drawingareabackground"        :DrawingAreaBackground        =hexvl(cm03_st)
      if cm02_st.lower()=="drawingareacontrastcolor1"    :DrawingAreaContrastColor1    =hexvl(cm03_st)
      if cm02_st.lower()=="drawingareacontrastcolor2"    :DrawingAreaContrastColor2    =hexvl(cm03_st)
      if cm02_st.lower()=="drawingareacontrastcolor3"    :DrawingAreaContrastColor3    =hexvl(cm03_st)
      if cm02_st.lower()=="drawingareacontrastcolor4"    :DrawingAreaContrastColor4    =hexvl(cm03_st)
      if cm02_st.lower()=="scrolledlistbackground"       :ScrolledListBackground       =hexvl(cm03_st)
      if cm02_st.lower()=="textbackground"               :TextBackground               =hexvl(cm03_st)
      if cm02_st.lower()=="highlightcolor1"              :HighlightColor1              =hexvl(cm03_st)
      if cm02_st.lower()=="highlightcolor2"              :HighlightColor2              =hexvl(cm03_st)
      if cm02_st.lower()=="highlightcolor3"              :HighlightColor3              =hexvl(cm03_st)
      if cm02_st.lower()=="highlightcolor4"              :HighlightColor4              =hexvl(cm03_st)
      if cm02_st.lower()=="highlightcolor5"              :HighlightColor5              =hexvl(cm03_st)
      if cm02_st.lower()=="highlightcolor6"              :HighlightColor6              =hexvl(cm03_st)
      if cm02_st.lower()=="highlightcolor7"              :HighlightColor7              =hexvl(cm03_st)
      if cm02_st.lower()=="highlightcolor8"              :HighlightColor8              =hexvl(cm03_st)
      if cm02_st.lower()=="wmbackground"                 :WMBackground                 =hexvl(cm03_st)
      if cm02_st.lower()=="wmforeground"                 :WMForeground                 =hexvl(cm03_st)
      if cm02_st.lower()=="wmactivebackground"           :WMActiveBackground           =hexvl(cm03_st)
      if cm02_st.lower()=="wmactiveforeground"           :WMActiveForeground           =hexvl(cm03_st)
      if cm02_st.lower()=="textselectedbackground"       :TextSelectedBackground       =hexvl(cm03_st)
      if cm02_st.lower()=="textselectedforeground"       :TextSelectedForeground       =hexvl(cm03_st)
      if cm02_st.lower()=="indicatorlightcolor"          :IndicatorLightColor          =hexvl(cm03_st)
      if cm02_st.lower()=="progressindicatorcolor"       :ProgressIndicatorColor       =hexvl(cm03_st)
      if cm02_st.lower()=="selectfillcolor"              :SelectFillColor              =hexvl(cm03_st)
      if cm02_st.lower()=="redColor"                     :RedColor                     =hexvl(cm03_st)
      if cm02_st.lower()=="orangecolor"                  :OrangeColor                  =hexvl(cm03_st)
      if cm02_st.lower()=="yellowcolor"                  :YellowColor                  =hexvl(cm03_st)
      if cm02_st.lower()=="greencolor"                   :GreenColor                   =hexvl(cm03_st)
      if cm02_st.lower()=="bluecolor"                    :BlueColor                    =hexvl(cm03_st)
      if cm02_st.lower()=="browncolor"                   :BrownColor                   =hexvl(cm03_st)
      if cm02_st.lower()=="purplecolor"                  :PurpleColor                  =hexvl(cm03_st)
      if cm02_st.lower()=="errorcolor"                   :ErrorColor                   =hexvl(cm03_st)
      if cm02_st.lower()=="warningcolor"                 :WarningColor                 =hexvl(cm03_st)
      if cm02_st.lower()=="informationcolor"             :InformationColor             =hexvl(cm03_st)
      if cm02_st.lower()=="alternatebackground1"         :AlternateBackground1         =hexvl(cm03_st)
      if cm02_st.lower()=="alternatebackground2"         :AlternateBackground2         =hexvl(cm03_st)
      if cm02_st.lower()=="alternatebackground3"         :AlternateBackground3         =hexvl(cm03_st)
      if cm02_st.lower()=="alternatebackground4"         :AlternateBackground4         =hexvl(cm03_st)
      if cm02_st.lower()=="alternatebackground5"         :AlternateBackground5         =hexvl(cm03_st)
      if cm02_st.lower()=="alternatebackground6"         :AlternateBackground6         =hexvl(cm03_st)
      if cm02_st.lower()=="disabledtextforeground"       :DisabledTextForeground       =hexvl(cm03_st)
      if cm02_st.lower()=="lightradiofillcolor"          :LightRadioFillColor          =hexvl(cm03_st)
      if cm02_st.lower()=="disabledcheckcolor"           :DisabledCheckColor           =hexvl(cm03_st)
      if cm02_st.lower()=="pixmapbuttonfillcolor"        :PixmapButtonFillColor        =hexvl(cm03_st)
      if cm02_st.lower()=="pixmapbuttonbottomshadowcolor":PixmapButtonBottomShadowColor=hexvl(cm03_st)
      if cm02_st.lower()=="pixmapbuttontopshadowcolor"   :PixmapButtonTopShadowColor   =hexvl(cm03_st)
      if debug==1:print "palette file "+fovl_stl[foid]+" readed. Lines readed:"+str(lcntr)
    inpfile.close()
  #- testing
  if debug==1:print fixhxc(WMBackground)
  #----------------------------------------------------------------------------------------
  #- next step ----------------------------------------------------------------------------
  clq_stl=[""]*9 #- dim clq_stl[9]
  idx_stl=[""]*9 #- dim idx_stl[9]
  cctn_stl=[""]*15 #- dim cctn_stl[15]
  #--------------------- brighter <--X--> darker -------------------------------------------
  #- substituir depois textfieldbackground para listbackground
  clq_stl[1]="252120";idx_stl[1]="2345678" #- BasicBackground        (background)
  clq_stl[2]="48485B";idx_stl[2]="GHIJKLM" #- ButtonBackground       (button)
  clq_stl[3]="252120";idx_stl[3]="NOPQRST" #- ScrollBarTroughColor   (scroll)
  clq_stl[4]="DCAC81";idx_stl[4]="UVWXYZ#" #- TextFieldBackground    (entry)
  clq_stl[5]="DCAC81";idx_stl[5]="ghijklm" #- ProgressIndicatorColor (progressbar)

  clq_stl[6]="DCAC81";idx_stl[6]="nopqrst" #- WMActiveBackground    (window border active)
  clq_stl[7]="DCAC81";idx_stl[7]="uvwxyz>" #- WMBackground          (window border inactive)

  clq_stl[1]=fixhex(BasicBackground,6)
  clq_stl[2]=fixhex(ButtonBackground,6)
  clq_stl[3]=fixhex(ScrollBarTroughColor,6)
  clq_stl[4]=fixhex(TextFieldBackground,6)
  clq_stl[5]=fixhex(ProgressIndicatorColor,6)

  clq_stl[6]=fixhex(WMActiveBackground,6)
  clq_stl[7]=fixhex(WMBackground ,6)

  #cctn_stl[0]=" 38 1\","
  cctn_stl[0]=cctn_stl[0]+"\". c None\",\n\"* c "
  cctn_stl[0]=cctn_stl[0]+fixhxc(CheckColor)
  cctn_stl[0]=cctn_stl[0]+"\",\n\"+ c "
  cctn_stl[0]=cctn_stl[0]+fixhxc(RadioColor)
  cctn_stl[0]=cctn_stl[0]+"\","
  for pqt in range(1,8,1):
    cctn_stl[pqt]=""
    z_st="\""+idx_stl[pqt][0]+" c #"+shade(clq_stl[pqt],"w",.25)+"\",\n"
    cctn_stl[pqt]=cctn_stl[pqt]+z_st
    z_st="\""+idx_stl[pqt][1]+" c #"+shade(clq_stl[pqt],"w",.5) +"\",\n"
    cctn_stl[pqt]=cctn_stl[pqt]+z_st
    z_st="\""+idx_stl[pqt][2]+" c #"+shade(clq_stl[pqt],"w",.75)+"\",\n"
    cctn_stl[pqt]=cctn_stl[pqt]+z_st
    z_st="\""+idx_stl[pqt][3]+" c #"+shade(clq_stl[pqt],"w",1)  +"\",\n"
    cctn_stl[pqt]=cctn_stl[pqt]+z_st
    z_st="\""+idx_stl[pqt][4]+" c #"+shade(clq_stl[pqt],"k",.75)+"\",\n"
    cctn_stl[pqt]=cctn_stl[pqt]+z_st
    z_st="\""+idx_stl[pqt][5]+" c #"+shade(clq_stl[pqt],"k",.5) +"\",\n"
    cctn_stl[pqt]=cctn_stl[pqt]+z_st
    z_st="\""+idx_stl[pqt][6]+" c #"+shade(clq_stl[pqt],"k",.25)+"\","
    cctn_stl[pqt]=cctn_stl[pqt]+z_st
  #----------------------------------------------------------------------------------------
  #- splitting sqc_pekwm_template.txt to all that files and replacing their string to colours ----
  print "splitting txttemplate into files..."
  tm_st="./sqc_pekwm_template.txt"
  firstcrop=0
  inpfile=open(finp_st,"r")
  #while eof(1)==0:
  while True:
    text_st=inpfile.readline()
    if len(text_st)==0:break
    text_st=" "+text_st+"      "
    text_st=text_st.replace("##TextForeground",fixhxc(TextForeground))
    text_st=text_st.replace("##TextSelectedBackground",fixhxc(TextSelectedBackground))
    text_st=text_st.replace("##BasicBackground",fixhxc(BasicBackground))
    text_st=text_st.replace("##ScrolledListBackground",fixhxc(ScrolledListBackground))
    text_st=text_st.replace("##WMBackground",fixhxc(WMBackground))
    text_st=text_st.replace("##WMActiveBackground",fixhxc(WMActiveBackground))
    text_st=text_st.replace("##WMForeground",fixhxc(WMForeground))
    text_st=text_st.replace("##WMActiveForeground",fixhxc(WMActiveForeground))

    text_st=text_st.replace("##--pbdep","52 1\",")
    text_st=text_st.replace("##--bkln","\n")

    if debug==1:print text_st
    readeddef=0
    cm01_st=locstrinfo(text_st," "," ");cm02_st=locstrinfo(text_st,"  "," ")
    if cm01_st.lower()=="--X--".lower():
      readeddef=1
      if firstcrop<>0:
        outfile.close()
      firstcrop=1
      outfile=open("./"+cm02_st,"w")
    if cm01_st[:16].lower()=="##--wholepalette".lower():
      readeddef=1
      for pqt in range (0,8,1):
        outfile.write(cctn_stl[pqt]+"\n")
        if debug==1:print "writing?"
    if readeddef==0 and firstcrop<>0:
      text_st=text_st.strip()
      outfile.write(text_st+"\n")
  inpfile.close()

  #----------------------------------------------------------------------------------------
  #- running shell commands ---------------------------------------------------------------
  print "running shell commands..."
  os.system("mkdirhier \"./sqc_"+themename_st+"\"")
  os.system("mv *.xpm ./sqc_"+themename_st)
  os.system("mv theme ./sqc_"+themename_st)
  os.system("cp "+chbcp_st+" ./sqc_"+themename_st)
  print "all conversion done!"
  #----------------------------------------------------------------------------------------
  #- end of converter code ----------------------------------------------------------------

if varghlp==1:
  print
  print"usage: python bcp2gnome.py [yourfile].BaseColorPalette"
  print"the theme folder result will appear neighbour to source file"
  print"(bcp2gnome [yourfile].BaseColorPalette (bcp2gnome in /usr/bin/) is not working yet)"
  print
if basepal==0:
  print
  print "Base.BaseColorPalette is missing"
  print "please check at current directory or at /usr/bin/"
  print
if txttmpl==0:
  print
  print "sqc_pekwm_template.txt is missing"
  print "please check at current directory or at /usr/bin/"
  print

print "ok"
#----------------------------------------------------------------------------------------
#- that's all !!! -----------------------------------------------------------------------
